/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.iec.edp.caf.commons.event.entity;

import io.iec.edp.caf.commons.event.CAFEventArgs;
import io.iec.edp.caf.commons.event.IEventListener;
import lombok.Data;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author Leon Huo
 * @Date: 2021/5/6
 */
@Data
public class MethodDelegate {
    /**
     * 要执行方法的对象
     */
    private IEventListener listener;
    /**
     * 要执行的方法名称
     */
    private String methodName;


    /**
     * 有参构造
     *
     * @param listener   要执行方法的对象
     * @param methodName 要执行的方法名称
     */
    public MethodDelegate(IEventListener listener, String methodName) {
        this.listener = listener;
        this.methodName = methodName;
    }


    /**
     * 通过反射执行方法
     */
    public void invoke(CAFEventArgs e) {
        try {
            Method method = this.listener.getClass().getMethod(this.getMethodName(), e.getClass());
            method.invoke(this.getListener(), e);
        } catch (InvocationTargetException invokeEx) {
            throw new RuntimeException(invokeEx.getTargetException().getCause().getMessage(), invokeEx);
        } catch (Exception ex) {
            throw new RuntimeException(ex.getMessage(), ex);
        }
    }
}
